/*
 *
 *  Copyright (C) 2010 Tal Eisenberg
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package tal.drivechain.chain.shell;

import tal.drivechain.chain.ChainNode;
import tal.drivechain.chain.NodeListener;
import tal.drivechain.plugin.Channel;
import tal.drivechain.variable.Variable;

/**
 *
 * @author eisental
 */
public class NodeSpy extends Spy implements NodeListener {
    private ChainNode node = null;
    private Variable lastReceived, lastSent;

    @Override
    public void setupSpy(String criteria) {
        node = chain.getNodeByPath(criteria);
        if (node==null) throw new IllegalArgumentException("Node " + criteria + " does not exist.");
        node.addNodeListener(this);
    }

    @Override
    public void destroy() {
        node.removeNodeListener(this);
    }

    @Override
    public String report() {
        String ret = node.getName() + "\n";
        ret += ("Last RECEIVED message: " + (lastReceived==null?"none recorded":lastReceived.toString(node))) + "\n";
        ret += ("Last SENT message: " + (lastSent==null?"none recorded":lastSent.toString(node))) + "\n";
        return ret;
    }

    public void nameChanged(ChainNode src) {
    }

    public void messageReceived(ChainNode src, Variable var, Channel channel, long timestamp) {
        out.println("spy: " + node.getName() + " received: " + var.toString(src) + " (" + channel.getName() + " channel)");
        lastReceived = var;
    }

    public void messageSent(ChainNode src, Variable var, long timestamp) {
        out.println("spy: " + node.getName() + " sent: " + var.toString(src));
        lastSent = var;
    }

    public void propertyChanged(ChainNode src, String name, Object value) {
    }

    public void connectionsChanged(ChainNode src) {
    }

    public void metaChanged(ChainNode src) {
    }

    public void nodeDestroyed(ChainNode src) {
        out.println("spy: " + node.getName() + " is destroyed.");
        this.destroy();
    }

    public void nodeMoved(ChainNode src) {
    }

    @Override
    public String getName() {
        return node.getName();
    }

}
